<template>
  <view class="container">
    <!-- 基础信息表单 -->
    <view class="info-card form-card">
      <u--form :model="model" ref="uForm" :rules="rules" label-width="100px">
        <u-form-item label="标题" prop="title" required>
          <u-input v-model="model.title" placeholder="请输入标题" border="surround"></u-input>
        </u-form-item>

        <u-form-item label="描述信息" prop="FloorInfo">
          <u--textarea v-model="model.description" placeholder="例如：我希望有个功能，XXX"></u--textarea>
        </u-form-item>
      </u--form>
    </view>

    <!-- 图片上传 -->
    <view class="info-card form-card">
      <view class="section-title">
        <u-icon name="camera" color="#06b6d4" size="18"></u-icon>
        <text class="title-text">图片</text>
      </view>
      <view class="upload-section">
        <text class="upload-desc">请上传图片（最多3张）</text>
        <view class="upload-grid">
          <view class="upload-item" v-for="(image, index) in uploadedImages" :key="index">
            <u-image :src="image" width="200rpx" height="200rpx" border-radius="16rpx" mode="aspectFill"></u-image>
            <view class="delete-btn" @click="deleteImage(index)">
              <u-icon name="close" color="#fff" size="12"></u-icon>
            </view>
          </view>
          <view class="upload-placeholder" v-if="uploadedImages.length < 5" @click="chooseImage">
            <u-icon name="plus" color="#94a3b8" size="32"></u-icon>
            <text class="upload-text">添加图片</text>

          </view>
        </view>
      </view>
    </view>
    <!-- 底部提交按钮 -->
    <view class="bottom-action-bar">
      <u-button type="primary" shape="circle" :custom-style="submitBtnStyle" @click="submitForm" :loading="isSubmitting">
        {{ isSubmitting ? '提交中...' : '提交反馈' }}
      </u-button>
    </view>


    <!-- 提示组件 -->
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        isSubmitting: false,
        model: {
          title: '',
          address: '',
          position: '',
          description: '' // 新增联系电话字段
        },

        selectedTags: [],
        uploadedImages: [],

        // 表单验证规则
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ]
        },
        submitBtnStyle: {
          width: '100%',
          background: 'linear-gradient(135deg, #0ea5e9, #06b6d4)',
          border: 'none',
          height: '88rpx',
          fontSize: '32rpx'
        }
      }
    },
    computed: {
      locationText() {
        if (this.model.Province && this.model.City && this.model.District) {
          return `${this.model.Province} ${this.model.City} ${this.model.District}`;
        }
        return '';
      }
    },
    methods: {
      // 地区选择确认
      onLocationConfirm(e) {
        const province = this.locationOptions[e.index[0]];
        const city = province.children[e.index[1]];
        const district = city.children ? city.children[e.index[2]] : null;

        this.model.Province = province.name;
        this.model.City = city.name;
        this.model.District = district ? district.name : '';
        this.showLocationSelector = false;
      },

      // 切换标签选择
      toggleTag(tag) {
        const index = this.selectedTags.indexOf(tag);
        if (index > -1) {
          this.selectedTags.splice(index, 1);
        } else {
          if (this.selectedTags.length < 8) { // 限制标签数量
            this.selectedTags.push(tag);
          } else {
            this.$refs.uToast.show({
              title: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 切换自定义标签输入
      toggleCustomTagInput() {
        this.showCustomTagInput = !this.showCustomTagInput;
        if (!this.showCustomTagInput) {
          this.customTag = '';
        }
      },

      // 添加自定义标签
      addCustomTag() {
        if (this.customTag.trim() && !this.selectedTags.includes(this.customTag.trim())) {
          if (this.selectedTags.length < 8) {
            this.selectedTags.push(this.customTag.trim());
            this.customTag = '';
            this.showCustomTagInput = false;
          } else {
            this.$refs.uToast.show({
              title: '最多只能选择8个标签',
              type: 'warning'
            });
          }
        }
      },

      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 5 - this.uploadedImages.length, // 最多5张
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            this.uploadedImages = this.uploadedImages.concat(res.tempFilePaths);
          }
        });
      },

      // 删除图片
      deleteImage(index) {
        this.uploadedImages.splice(index, 1);
      },

      // 提交表单
      async submitForm() {
        try {
          // 表单验证
          const valid = await this.validateForm();
          if (!valid) return;

          this.isSubmitting = true;

          // 构建提交数据
          const submitData = {
            ...this.formData,
            Area: parseFloat(this.model.Area),
            Price: parseFloat(this.model.Price),
            Position: {
              Latitude: this.model.Position.Latitude ? parseFloat(this.model.Position.Latitude) : null,
              Longitude: this.model.Position.Longitude ? parseFloat(this.model.Position.Longitude) : null
            },
            TagsJson: JSON.stringify(this.selectedTags),
            ImageUrls: JSON.stringify(this.uploadedImages),
            IsEnabled: true, // 默认启用
            Id: Date.now().toString(), // 模拟ID
            // 其他默认或后端生成的字段
            createTime: new Date().toISOString(),
            createUserId: "0",
            createUserName: "admin"
          };

          console.log('提交数据:', submitData);

          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 2000));

          this.$refs.uToast.show({
            title: '租房信息录入成功',
            type: 'success'
          });

          // 延迟跳转
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);

        } catch (error) {
          console.error('提交失败:', error);
          this.$refs.uToast.show({
            title: '提交失败，请重试',
            type: 'error'
          });
        } finally {
          this.isSubmitting = false;
        }
      },

      // 表单验证
      async validateForm() {
        try {
          // 基础信息验证
          await this.$refs.uForm.validate();

          // 地址验证
          if (!this.model.Province || !this.model.City || !this.model.District) {
            this.$refs.uToast.show({
              title: '请选择所在省市区',
              type: 'warning'
            });
            return false;
          }
          if (!this.model.Address.trim()) {
            this.$refs.uToast.show({
              title: '请输入详细地址',
              type: 'warning'
            });
            return false;
          }

          // 经纬度验证 (如果填写了，则必须是数字)
          if (this.model.Position.Latitude && isNaN(parseFloat(this.model.Position.Latitude))) {
            this.$refs.uToast.show({
              title: '纬度必须为数字',
              type: 'warning'
            });
            return false;
          }
          if (this.model.Position.Longitude && isNaN(parseFloat(this.model.Position.Longitude))) {
            this.$refs.uToast.show({
              title: '经度必须为数字',
              type: 'warning'
            });
            return false;
          }

          // 图片验证
          if (this.uploadedImages.length === 0) {
            this.$refs.uToast.show({
              title: '请至少上传一张租房图片',
              type: 'warning'
            });
            return false;
          }

          return true;
        } catch (error) {
          console.error('表单验证失败:', error);
          return false;
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    min-height: 100vh;
    background: #f8fafc;
    display: flex;
    flex-direction: column;
  }


  .info-card {
    background: white;
    border-radius: 24rpx;
    margin: 0 10rpx 10rpx;
    padding: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
    border: 1rpx solid #f1f5f9;
  }

  .welcome-card {
    margin-top: 24rpx;

    .welcome-header {
      display: flex;
      align-items: center;
      gap: 16rpx;
      margin-bottom: 16rpx;

      .welcome-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #1e293b;
      }
    }

    .welcome-desc {
      font-size: 26rpx;
      color: #64748b;
      line-height: 1.5;
    }
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 12rpx;
    font-size: 28rpx;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 32rpx;
  }

  .tags-section {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 16rpx;
    gap: 10upx;
  }

  .custom-tag-input {
    margin-bottom: 16rpx;
  }

  .upload-section {
    .upload-desc {
      font-size: 26rpx;
      color: #64748b;
      margin-bottom: 24rpx;
      display: block;
    }

    .upload-grid {
      display: flex;
      flex-wrap: wrap;
      gap: 24rpx;

      .upload-item {
        position: relative;

        .delete-btn {
          position: absolute;
          top: -12rpx;
          right: -12rpx;
          width: 48rpx;
          height: 48rpx;
          background: #ef4444;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 4rpx 12rpx rgba(239, 68, 68, 0.3);
        }
      }

      .upload-placeholder {
        width: 200rpx;
        height: 200rpx;
        background: #f8fafc;
        border: 2rpx dashed #cbd5e1;
        border-radius: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 12rpx;

        .upload-text {
          font-size: 24rpx;
          color: #94a3b8;
        }
      }
    }
  }

  .bottom-action-bar {
    background: white;
    padding: 24rpx 32rpx;
    border-top: 1rpx solid #f1f5f9;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
    z-index: 100;
  }
</style>